package top.itmeans.yes.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import top.itmeans.yes.common.exception.Asserts;
import top.itmeans.yes.entity.Member;
import top.itmeans.yes.mapper.MemberMapper;
import top.itmeans.yes.portal.domain.MemberDetails;
import top.itmeans.yes.portal.service.MemberCacheService;
import top.itmeans.yes.portal.service.MemberService;
import top.itmeans.yes.security.util.JwtTokenUtil;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 普通会员表 服务实现类
 * </p>
 *
 * @author Yiming.Cao
 * @since 2022-05-05
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MemberServiceImpl.class);
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MemberCacheService memberCacheService;
    @Value("${redis.key.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Override
    public Member getByUsername(String username) {
        Map<String,Object> columnMap = new HashMap<>(4);
        columnMap.put("username",username);
        List<Member> memberList = this.listByMap(columnMap);
        if (!CollectionUtils.isEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }

    @Override
    public void register(String username, String password, String telephone, String authCode) {
        //验证验证码
        if(!verifyAuthCode(authCode,telephone)){
            Asserts.fail("验证码错误");
        }
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Member::getUsername,username).or().eq(Member::getPhone,telephone);
        List<Member> Members = memberMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(Members)) {
            Asserts.fail("该用户已经存在");
        }
        //没有该用户进行添加操作
        Member member = new Member();
        member.setUsername(username);
        member.setPhone(telephone);
        member.setPassword(passwordEncoder.encode(password));
        member.setCreateTime(LocalDateTime.now());
        memberMapper.insert(member);
        member.setPassword(null);
    }

    @Override
    public String generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    @Override
    public void updatePassword(String telephone, String password, String authCode) {
        Map<String,Object> columnMap = new HashMap<>(4);
        columnMap.put("phone",telephone);
        List<Member> memberList = this.listByMap(columnMap);
        if(CollectionUtils.isEmpty(memberList)){
            Asserts.fail("该账号不存在");
        }
        //验证验证码
        if(!verifyAuthCode(authCode,telephone)){
            Asserts.fail("验证码错误");
        }
        Member member = memberList.get(0);
        member.setPassword(passwordEncoder.encode(password));
        memberMapper.updateById(member);
    }

    @Override
    public Member getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
        return memberDetails.getMember();
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        Member record=new Member();
        record.setId(id);
        memberMapper.updateById(record);
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        Member member = getByUsername(username);
        if(member!=null){
            return new MemberDetails(member);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    /** 对输入的验证码进行校验 */
    private boolean verifyAuthCode(String authCode, String telephone){
        if(StringUtils.isEmpty(authCode)){
            return false;
        }
        String realAuthCode = memberCacheService.getAuthCode(telephone);
        return authCode.equals(realAuthCode);
    }

}
